import sys
from socket import *
import getpass
import re

ADDR = ("127.0.0.1", 9999)
client = socket()
client.connect(ADDR)


# 注册
def do_register():
    while True:
        username = input("user:")
        password = getpass.getpass("password:")
        password1 = getpass.getpass("input you password again:")
        if password != password1:
            print("两次密码输入不致")
            continue
        if " " in username:
            print("username can not contain space")
            username = "".join(username.split(" "))
        elif " " in password:
            print("password can not contain space")
            password = "".join(password)
        msg = "R %s %s" % (username, password)
        client.send(msg.encode("utf-8"))
        data = client.recv(1024).decode()
        if data == "OK":
            print("注册成功")
            login(username)
        else:
            print("注册失败")
        return

# 登录
def do_login():
    while True:
        username = input("username:")
        password = getpass.getpass("password:")
        if " " in username:
            print("username can not contain space")
            username = "".join(username.split(" "))
        elif " " in password:
            print("password can not contain space")
            password = "".join(password)
        msg = "L %s %s" % (username, password)
        client.send(msg.encode())
        data = client.recv(1024).decode()
        if data == "OK":
            print("登录成功")
            login(username)
        else:
            print("登录失败")
        return

# 查询单词界面
def login(name):
    while True:
        print("Enter your Choice"
              "1. 查询单词"
              "2. 历史记录"
              "3. 注销登录")
        cmd = input("msg>:")
        if cmd == "1":
            do_query(name)
        elif cmd == "2":
            do_history(name)
        elif cmd == "3":
            return

# 查询单词逻辑实现
def do_query(name):
    while True:
        word = input("word:")
        if word == "##":
            break
        msg = "Q %s %s" % (name, word)
        client.send(msg.encode())  # 发送请求
        data = client.recv(2048).decode()
        print(data)

# 查询历史记录逻辑实现
def do_history(name):
    msg="H %s" %(name)
    client.send(msg.encode())
    data = client.recv(2048)
    print(data.decode())

# 主程序
def main():
    while True:
        print("Enter your Choice"
              "1. 注册"
              "2. 登录"
              "3. 退出")
        cmd = input("msg>:")
        if cmd == "1":
            do_register()
        elif cmd == "2":
            do_login()
        elif cmd == "3":
            client.send("E".encode())
            sys.exit("谢谢使用")
        else:
            print("请输入正确的指令")


if __name__ == "__main__":
    main()
